﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace Easy.Common.RegisterType
{
    public class RegisterTypeAnalyser
    {
        /// <summary>
        /// 解析指定的程序集，返回需要注册的类型信息。
        /// </summary>
        public static List<RegisterTypeInfo> Analyze(Assembly assembly)
        {
            CheckHelper.NotNull(assembly, "assembly");

            return GetRegisterTypeInfos(assembly);
        }


        #region Private

        private static List<RegisterTypeInfo> GetRegisterTypeInfos(Assembly assembly)
        {
            var registerTypeInfos = new List<RegisterTypeInfo>();

            registerTypeInfos.AddRange(GetRegisterTypeInfos(assembly.GetTypes()));

            return registerTypeInfos;
        }

        private static List<RegisterTypeInfo> GetRegisterTypeInfos(Type[] types)
        {
            CheckHelper.ArrayNotHasNull(types, "types");

            var registerTypeInfos = new List<RegisterTypeInfo>();

            foreach (Type t in types)
            {
                var attr = t.GetCustomAttribute<RegisterTypeAttribute>(false);

                if (attr != null)
                {
                    registerTypeInfos.Add(new RegisterTypeInfo(t, attr));
                }
            }

            return registerTypeInfos;
        }

        #endregion
    }
}
